<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/layout :: head('我的借阅')}"></head>
<body>
    <!-- 导航栏 -->
    <nav th:replace="~{fragments/layout :: navbar}"></nav>
    
    <!-- 页面内容 -->
    <div th:replace="~{fragments/layout :: content(~{::main})}">
        <main>
            <h2 class="mb-4">我的借阅记录</h2>
            
            <!-- 借阅状态统计 -->
            <div class="row mb-4">
                <div class="col-md-4">
                    <div class="card text-white bg-primary">
                        <div class="card-body">
                            <h5 class="card-title">当前借阅</h5>
                            <p class="card-text display-4" th:text="${currentLoansCount}">0</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card text-white bg-success">
                        <div class="card-body">
                            <h5 class="card-title">已归还</h5>
                            <p class="card-text display-4" th:text="${returnedLoansCount}">0</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card text-white bg-danger">
                        <div class="card-body">
                            <h5 class="card-title">逾期未还</h5>
                            <p class="card-text display-4" th:text="${overdueLoansCount}">0</p>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 借阅记录表格 -->
            <div class="card">
                <div class="card-header">
                    <ul class="nav nav-tabs card-header-tabs" id="loansTab" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="current-tab" data-bs-toggle="tab" data-bs-target="#current" type="button" role="tab">当前借阅</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="history-tab" data-bs-toggle="tab" data-bs-target="#history" type="button" role="tab">借阅历史</button>
                        </li>
                    </ul>
                </div>
                <div class="card-body">
                    <div class="tab-content" id="loansTabContent">
                        <!-- 当前借阅 -->
                        <div class="tab-pane fade show active" id="current" role="tabpanel">
                            <div th:if="${#lists.isEmpty(currentLoans)}" class="text-center py-5">
                                <p class="text-muted">您当前没有借阅任何图书</p>
                                <a th:href="@{/books/list}" class="btn btn-primary">浏览图书</a>
                            </div>
                            
                            <div class="table-responsive" th:unless="${#lists.isEmpty(currentLoans)}">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>图书</th>
                                            <th>借阅日期</th>
                                            <th>应还日期</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr th:each="loan : ${currentLoans}">
                                            <td>
                                                <a th:href="@{/books/view/{id}(id=${loan.book.id})}" class="text-decoration-none">
                                                    <strong th:text="${loan.book.title}">图书标题</strong>
                                                </a>
                                                <div class="text-muted" th:text="${loan.book.author}">作者</div>
                                            </td>
                                            <td th:text="${#temporals.format(loan.borrowDate, 'yyyy-MM-dd')}">2023-01-01</td>
                                            <td th:text="${#temporals.format(loan.dueDate, 'yyyy-MM-dd')}">2023-01-15</td>
                                            <td>
                                                <span th:if="${loan.status.name() == 'BORROWED'}" class="badge bg-primary">借阅中</span>
                                                <span th:if="${loan.status.name() == 'OVERDUE'}" class="badge bg-danger">已逾期</span>
                                            </td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-success return-book-btn" th:data-loan-id="${loan.id}" th:data-book-title="${loan.book.title}" th:data-borrow-date="${#temporals.format(loan.borrowDate, 'yyyy-MM-dd')}" th:data-due-date="${#temporals.format(loan.dueDate, 'yyyy-MM-dd')}">
                                                    <i class="fas fa-undo me-1"></i> 归还
                                                </button>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        
                        <!-- 借阅历史 -->
                        <div class="tab-pane fade" id="history" role="tabpanel">
                            <div th:if="${#lists.isEmpty(historyLoans)}" class="text-center py-5">
                                <p class="text-muted">您没有历史借阅记录</p>
                            </div>
                            
                            <div class="table-responsive" th:unless="${#lists.isEmpty(historyLoans)}">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>图书</th>
                                            <th>借阅日期</th>
                                            <th>归还日期</th>
                                            <th>状态</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr th:each="loan : ${historyLoans}">
                                            <td>
                                                <a th:href="@{/books/view/{id}(id=${loan.book.id})}" class="text-decoration-none">
                                                    <strong th:text="${loan.book.title}">图书标题</strong>
                                                </a>
                                                <div class="text-muted" th:text="${loan.book.author}">作者</div>
                                            </td>
                                            <td th:text="${#temporals.format(loan.borrowDate, 'yyyy-MM-dd')}">2023-01-01</td>
                                            <td th:text="${loan.returnDate != null ? #temporals.format(loan.returnDate, 'yyyy-MM-dd') : '-'}">2023-01-10</td>
                                            <td>
                                                <span class="badge bg-success">已归还</span>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- 历史记录分页 -->
                            <nav th:if="${historyTotalPages > 1}" class="mt-3">
                                <ul class="pagination justify-content-center">
                                    <li class="page-item" th:classappend="${historyCurrentPage == 0} ? 'disabled' : ''">
                                        <a class="page-link" th:href="@{/loans/my(page=${historyCurrentPage - 1})}" aria-label="上一页">
                                            <span aria-hidden="true">&laquo;</span>
                                        </a>
                                    </li>
                                    <li class="page-item" th:each="i : ${#numbers.sequence(0, historyTotalPages - 1)}" 
                                        th:classappend="${historyCurrentPage == i} ? 'active' : ''">
                                        <a class="page-link" th:href="@{/loans/my(page=${i})}" th:text="${i + 1}">1</a>
                                    </li>
                                    <li class="page-item" th:classappend="${historyCurrentPage == historyTotalPages - 1} ? 'disabled' : ''">
                                        <a class="page-link" th:href="@{/loans/my(page=${historyCurrentPage + 1})}" aria-label="下一页">
                                            <span aria-hidden="true">&raquo;</span>
                                        </a>
                                    </li>
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
    
    <!-- 页脚 -->
    <footer th:replace="~{fragments/layout :: footer}"></footer>
    
    <!-- 脚本 -->
    <div th:replace="~{fragments/layout :: scripts}"></div>
    <!-- 归还确认模态框 -->
    <div class="modal fade" id="returnConfirmModal" tabindex="-1" aria-labelledby="returnConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-light">
                    <h5 class="modal-title" id="returnConfirmModalLabel">确认归还图书</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="text-center mb-3">
                        <i class="fas fa-book text-primary" style="font-size: 2rem;"></i>
                    </div>
                    <div class="alert alert-info">
                        <p class="mb-0">您确定要归还以下图书吗？</p>
                    </div>
                    <div class="card mb-3">
                        <div class="card-body">
                            <h5 class="card-title" id="returnBookTitle">图书标题</h5>
                            <p class="card-text">借阅日期: <span id="returnBorrowDate">2023-01-01</span></p>
                            <p class="card-text">应还日期: <span id="returnDueDate">2023-01-15</span></p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i> 取消
                    </button>
                    <form id="returnForm" th:action="@{/loans/return}" method="post">
                        <input type="hidden" id="loanId" name="loanId" value="">
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-check me-1"></i> 确认归还
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化模态框
            const returnModal = new bootstrap.Modal(document.getElementById('returnConfirmModal'));
            
            // 归还按钮点击事件
            const returnButtons = document.querySelectorAll('.return-book-btn');
            returnButtons.forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    const loanId = this.getAttribute('data-loan-id');
                    const bookTitle = this.getAttribute('data-book-title');
                    const borrowDate = this.getAttribute('data-borrow-date');
                    const dueDate = this.getAttribute('data-due-date');
                    
                    // 设置模态框中的数据
                    document.getElementById('returnBookTitle').textContent = bookTitle;
                    document.getElementById('returnBorrowDate').textContent = borrowDate;
                    document.getElementById('returnDueDate').textContent = dueDate;
                    document.getElementById('loanId').value = loanId;
                    
                    // 显示模态框
                    returnModal.show();
                });
            });
            
            // 处理归还表单提交
            const returnForm = document.getElementById('returnForm');
            returnForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                // 禁用按钮防止重复提交
                const submitButton = this.querySelector('button[type="submit"]');
                const originalText = submitButton.innerHTML;
                submitButton.disabled = true;
                submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
                
                const formData = new FormData(this);
                const modalBody = document.querySelector('#returnConfirmModal .modal-body');
                
                // 发送归还请求
                fetch('/loans/return', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (response.ok) {
                        // 创建成功消息
                        const successAlert = document.createElement('div');
                        successAlert.className = 'alert alert-success mt-3';
                        successAlert.innerHTML = '<i class="fas fa-check-circle me-2"></i>图书已成功归还！';
                        
                        // 替换模态框内容
                        modalBody.innerHTML = '';
                        modalBody.appendChild(successAlert);
                        
                        // 替换按钮
                        const modalFooter = document.querySelector('#returnConfirmModal .modal-footer');
                        modalFooter.innerHTML = '<button type="button" class="btn btn-primary" onclick="window.location.reload()">关闭并刷新</button>';
                        
                        // 1.5秒后自动刷新页面
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    } else {
                        throw new Error('归还操作失败');
                    }
                })
                .catch(error => {
                    // 恢复按钮状态
                    submitButton.disabled = false;
                    submitButton.innerHTML = originalText;
                    
                    // 显示错误消息
                    const errorAlert = document.createElement('div');
                    errorAlert.className = 'alert alert-danger mt-3';
                    errorAlert.innerHTML = '<i class="fas fa-exclamation-triangle me-2"></i>错误: ' + error.message;
                    
                    modalBody.appendChild(errorAlert);
                });
            });
        });
    </script>
</body>
</html>
